package code.utils
{
	
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	import flash.utils.getTimer;
	
	/**倒计时类
	 *作者 xyz
	 */
	
	public class CountdownTimer extends EventDispatcher
	{
		private var timer:Timer;
		private var _restTime:int;
		private var _beginTime:int;
		private var _beginRestTime:int;
		/**
		 * __restTime:剩余秒数
		 */
		public function CountdownTimer(__restTime:int)
		{
			super(null);
			init(__restTime);
		}
		private function init(__restTime:int):void{
			_restTime = _beginRestTime = __restTime;
			_beginTime = getTimer();
			if(!timer){
				timer = new Timer(1000);
			}
			stop();
			timer.start();
			timer.addEventListener(TimerEvent.TIMER,_onTimer);
		}
		private function _onTimer(e:TimerEvent):void{
			_restTime = _beginRestTime - int((getTimer() - _beginTime)*.001);
			dispatchEvent(e);
			if(_restTime <= 0){
				dispatchEvent(new TimerEvent(TimerEvent.TIMER_COMPLETE));
				stop();
			}
		}
		//得到由剩余时间转换成的字符串“000：00：00”
//		public function get timeStr():String{
//			return DataFormatUtils.getTimeStrBySecond(_restTime);
//			//			var _time:int = _restTime*1000;
//			//			if(_time<0){
//			//				_time=0;
//			//			}
//			//			var hour:String = "" + TimeUtil.getTotalLeftHour(_time);
//			//			var minutes:String = String("00" + TimeUtil.getLeftMinute(_time)).substr(-2);
//			//			var second:String = String("00" + TimeUtil.getLeftSecond(_time)).substr(-2);
//			//			return hour+":"+minutes+":"+second;
//		}
		
		//获取剩余时间
		public function get restTime():int{
			return _restTime;
		}
		//重设剩余时间
		public function set restTime(v:int):void{
			init(v);
		}
		
		
		
		public function stop():void{
			timer.removeEventListener(TimerEvent.TIMER,_onTimer);
			timer.stop();
		}
	}
}